<template>
  <div>


    <el-form ref="formRef" :model="dataForm" label-width="10px" :inline="false" @submit.prevent>
      <el-form-item prop="userName" style="padding: 10px; margin-bottom: 10px" label="已选：" label-width="60px">
        <div class="select-box">
          <div class="tags-box" :style="{ height: tagHeight }">
            <div class="tags-main" id="tagsMain">
              <el-tag v-for="(item, index) in selectCheckList" :key="index" class="tags" closable
                @close="removeTab(index, item)">
                {{ item.label }}
              </el-tag>
            </div>
          </div>
          <div class="show-more" v-if="isShowBtn">
            <p v-show="tagHeight == '40px'" @click="tagHeight = 'auto'">展开</p>
            <p v-show="tagHeight == 'auto'" @click="tagHeight = '40px'">收缩</p>
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <div style="margin-bottom: 20px; width: 100%">
          <el-tabs v-model="tabsValue" class="demo-tabs">
            <el-tab-pane v-for="item in tabsList" :key="item.org" :label="item.label" :name="item.value">
            </el-tab-pane>
          </el-tabs>
        </div>
        <div v-show="tabsValue == 'people'" style="width: 100%">
          <el-row style="width: 100%; border: 1px solid #dcdfe6; border-radius: 5px">
            <el-col :span="12">
              <div class="head"></div>
              <div class="city-box">
                <orgTree @on-update="deptUpdate"></orgTree>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="head">
                <p>已选 {{ selectNum }}/{{ peopleList.length }}</p>
                <p @click="allCheck">全选</p>
              </div>
              <div class="selec-city">
                <el-form-item prop="userName" style="padding: 10px; margin-bottom: 10px">
                  <el-input v-model="dataForm.userName" placeholder="请输入名称搜索" clearable @input.self="searchHandle"
                    type="text" />
                </el-form-item>
                <div class="subject-con" v-loading="userLoading">
                  <div v-if="peopleList.length > 0">
                    <div v-for="(item, index) in peopleList" :key="index" class="subject-list">
                      <p class="search-list"><el-tooltip class="box-item" effect="dark"
                          :content="item.label + '_' + item.email + '( ' + (item.companyName || '') + (item.companyName ?'_':'') + (item.orgName || orgName) + ' )'"
                          placement="top">
                          {{ item.label }}_{{ item.email }} ({{ item.companyName || '' }}{{ item.companyName ?'_':'' }}{{  item.orgName || orgName }})
                        </el-tooltip></p>
                      <div class="check-box" @click="selectPeople(index, item)">
                        <img :src="selectIcon" alt v-if="item.isSelect" />
                        <img :src="noSelectIcon" alt v-else />
                      </div>
                    </div>
                  </div>
                  <div class="no-data" v-else>暂无数据</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        <!-- 岗位 -->
        <div class="subject-con" v-show="tabsValue == 'work'" style="width: 100%">
          <workPosition @on-update="updateWork"></workPosition>
        </div>
        <!-- 组织机构 -->
        <div class="org" v-show="tabsValue == 'org'" style="width: 100%" v-loading="orgLoading">
          <el-tree-v2 :data="treeData" ref="orgTreeRef" :check-strictly="true" :props="defaultProps2" :height="208"
            @check-change="checkChangeAllOrg">
            <template #default="{ node }">
              <div class="tree-box">
                <p>
                  <el-checkbox v-model="node.data.select" style="margin-right: 10px"
                    @change="selectCurCheck(node)" />{{ node.label }}
                </p>
                <p class="btn-box" v-if="node.children && node.children.length > 0">
                  <span>
                    <el-checkbox v-model="node.data.curSelect" label="全选下级"
                      @change="nodeCurrentAll(node, node.data.curSelect)" />
                  </span>
                  <span v-if="node.data.children">
                    <el-checkbox v-model="node.data.allSelect" label="全选子级"
                      @change="nodeSelectAll(node, node.data.allSelect)" />
                    {{ node.index }}
                  </span>
                </p>
              </div>
            </template>
          </el-tree-v2>
        </div>
      </el-form-item>
    </el-form>


  </div>
</template>
<script setup>
import api from "@/api/index";
import { ElMessage, ElMessageBox } from "element-plus";
import selectIcon from "@/assets/images/check_select.png";
import noSelectIcon from "@/assets/images/check_no_select.png";
import orgTree from "@/components/OrgLazy/index.vue";
import workPosition from "@/components/WorkPosition/index.vue";
import { unique } from "@/util/index";
import { useUserStore } from "@/store/modules/user";
import { nextTick, watch } from "vue";

const props = defineProps({
  scopeInfo: {
    type: Object,
    default: () => { },
  },
});

const defaultProps2 = ref({
  label: "sapDepartmentName",
  children: "children",
});

const tagHeight = ref("40px");

const dataForm = ref({
  userName: "",
});

const userStore = useUserStore();

const orgTreeRef = ref(null);

const defaultProps = ref({
  label: "label",
  children: "zones",
  isLeaf: "leaf",
});

const userLoading = ref(false);

const orgLoading = ref(false);

const peopleList = ref([]);

const subjectOldDataList = ref([]);

const formRef = ref(null);

const editableTabsValue = ref();

const selectCheckList = ref([]);

const membersIds = ref([]);

const departmentIds = ref(""); // ?登录帐户组织 id

const companiesIds = ref(""); // 组织机构id集合

const emit = defineEmits(["on-submit", "handleClose", "on-update"]);

const orgName = ref("");

const selectOrgList = ref([]);

const orgChildIds = ref([]);

const selectNum = computed(() => {
  let list = [];
  let ids = [];
  peopleList.value.forEach((item) => {
    if (item.isSelect) {
      list.push(item);
    }
  });
  let newList = selectCheckList.value.filter(
    (item) => item["sourceType"] != "user"
  );
  let userList = selectCheckList.value.filter(
    (item) => item["sourceType"] == "user"
  );
  let concatList = unique([...list, ...userList], "id");
  selectCheckList.value = [...newList, ...concatList];
  concatList.forEach((item) => {
    ids.push(item.id);
  });
  membersIds.value = ids;
  return list.length;
});

const isShowBtn = ref(false);

const tabsList = ref([
  { label: "组织机构", value: "org" },
  { label: "岗位", value: "work" },
  { label: "人员", value: "people" },
]);

const tabsValue = ref("org");

const positionsIds = ref([]); // 岗位 id

const treeData = ref([]);

const companiesList = ref([]); //组织机构选把择

const orgIds = ref([]);

watch(
  () => companiesList.value,
  (newVal, oldVal) => {
    let ids = [];
    newVal.forEach((item) => ids.push(item.id));
    companiesIds.value = ids;
  }
);

onMounted(() => {
  console.log('触发', props.scopeInfo)
  if (props.scopeInfo != "") {
    // 编辑回显
    try {
      let obj =
        typeof props.scopeInfo == "string"
          ? JSON.parse(props.scopeInfo)
          : props.scopeInfo;
      // if (obj.positionsIds.length > 0) { 
      positionsIds.value = obj.positionsIds
      console.log(obj.positionsIds, 'obj.positionsIds')
      workEcho(obj.positionsIds); //  岗位回显
      // }

      if (obj.membersIds.length > 0 && obj.userList) {
        // 人员回显
        // getUserList(obj.departmentIds).then(res => {
        //     if (res.length > 0) selectEcho(obj.membersIds, peopleList.value)
        // })
        selectCheckList.value = [...selectCheckList.value, ...obj.userList];
      }
      orgName.value = props.scopeInfo.orgName || "";
      //组织机构回显
      getAllCommayTree().then((res) => {
        if (res) {
          companiesIds.value = obj.companiesIds || [];
          //  orgTreeRef.value.setCheckedKeys(obj.companiesIds || []);
          orgIds.value = obj.companiesIds;
          selectOrg(treeData.value, obj.companiesIds);
          checkChangeAllOrg();
        }
      });
    } catch (error) { }
  } else {
    workEcho([])
    getAllCommayTree();
  }
});

// 给选中的对像打标记为 true
const selectOrg = (res, ids) => {
  let count = 0;
  let allCount = 0;
  res.forEach((item) => {
    if (ids.includes(item.id)) {
      item.label = item.sapDepartmentName;
      item.select = true;
      selectOrgList.value.push(item);
      count++;
    } else {
      item.select = false;

    }

    if (item.children) {
      const [curSelect, allSelect] = selectOrg(item.children, ids);
      item.curSelect = curSelect;
      item.allSelect = allSelect;
      if (item.curSelect) allCount++;
    } else if (item.select) {
      allCount++;
    }
  });
  return [res.length == count, res.length == allCount];
};

// 组织机构勾选操作
const selectCurCheck = (node) => {
  const status = node.data.select;
  console.log(status, 'statusstatus')
  const id = node.data.id;
  if (status) {
    orgIds.value.push(id);
  } else {
    let findId = orgIds.value.findIndex((item) => item == id);
    orgIds.value.splice(findId, 1);

  }
  selectOrgList.value = []
  selectOrg(treeData.value, orgIds.value);
  checkChangeAllOrg();
};
const getAllCommayTree = (type) => {
  orgLoading.value = true;
  return new Promise((resolve) => {
    api.user.allCompanyTree().then((res) => {
      treeData.value = res;
      nextTick(() => {
        orgLoading.value = false;
      })
      resolve(res);

    });
  });
};

// 岗位回显
const workEcho = (ids) => {
  let list = userStore.workerPositionList;
  if (ids && ids.length == 0) {
    list.forEach(item => item.isSelect = false)
  }
  let newList = selectEcho(ids, list);
  userStore.setWorkPosition(newList);
};

// 获取选中的数据
const selectEcho = (ids, list) => {
  let selectArr = [];
  ids.forEach((item) => {
    list.forEach((item2) => {
      if (item == item2.id) {
        item2["isSelect"] = true;
        selectArr.push(item2);
      }
    });
  });
  selectCheckList.value = [...selectCheckList.value, ...selectArr];

  return list;
};

// 关闭
const handleClose = () => {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  emit("handleClose");
};

// 全选
const allCheck = () => {
  let arr = peopleList.value.filter((item) => item["isSelect"]);
  if (arr.length == peopleList.value.length) {
    // 代表已全选 应该反选
    peopleList.value.forEach((item) => {
      item["isSelect"] = false;
    });
  } else {
    peopleList.value.forEach((item) => {
      item["isSelect"] = true;
    });
  }
};
// 选择用户
const selectPeople = (index, item) => {

  for (let k of selectCheckList.value) {
    // 如果存在 id 相同，就不向上增加
    if (k.sourceType == 'user' && k.id == item.id) return
  }
  peopleList.value[index]["isSelect"] = !peopleList.value[index]["isSelect"];
};

// 删除岗位
const deleteWork = (row) => {
  let list = userStore.workerPositionList;
  let index = list.findIndex((item) => item.id == row.id);
  list[index]["isSelect"] = !list[index]["isSelect"];
  userStore.setWorkPosition(list);
};

// 删除组织
const deleOrg = (row) => {
  let index = companiesList.value.findIndex((item) => item.id == row.id);
  let ids = [];
  if (index > -1) {
    companiesList.value.splice(index, 1);
    companiesList.value.forEach((item) => ids.push(item.id));
    companiesIds.value = ids;
    orgTreeRef.value.setCheckedKeys(ids);

  }
  let findId = orgIds.value.findIndex(item => item == row.id)
  if (findId > -1) orgIds.value.splice(findId, 1)
  selectOrg(treeData.value, orgIds.value)
};

const removeTab = (index, row) => {
  const obj = {
    work: deleteWork,
    org: deleOrg,
  };
  obj[row["sourceType"]] && obj[row["sourceType"]](row);

  selectCheckList.value.splice(index, 1);
};

// 选择组织 获取对应的工作人员
const deptUpdate = ([data]) => {
  if (data.label == orgName.value) return
  orgName.value = data.label;

  dataForm.value.userName = ''
  getUserList(data.departmentId);
};

const getUserList = (departmentId) => {
  peopleList.value = [];
  userLoading.value = true;
  return new Promise((resolve) => {
    departmentIds.value = departmentId;

    api.user.user_GetUsers({
      departmentId,
      name: "",
    }).then(res => {
      let backData = res.map((item) => {
        return {
          label: item.name,
          id: item.id,
          email: item.email,
          sourceType: "user",
          name: item.name,
          orgName: item.departmentName,
          companyName: item.companyName
        };
      });
      peopleList.value = backData;
      subjectOldDataList.value = backData;
      userLoading.value = false;
      resolve(backData);
    })

  });
};

// 搜索
const searchHandle = (val) => {
  // if (orgName.value != '') {
  //   // 如果通过组织机构查询 搜索就是当前机构的
  //     if (val == "") {
  //   peopleList.value = subjectOldDataList.value;
  // } else {
  //   peopleList.value = subjectOldDataList.value.filter((item) =>
  //     item.label.includes(val)
  //   );
  // }
  // } else {
  if (val && val != '') {
    // 查询所有
    api.user.user_GetUsers({
      departmentId: '',
      name: val || ''
    }).then(res => {
      let result = res.map(item => {
        return {
          label: item.name,
          orgName: item.departmentName,
          id: item.id,
          sourceType: 'user',
          email: item.email,
          companyName: item.companyName
        }
      })
      peopleList.value = result
    })
  }

  // }


};

const checkChangeAllOrg = () => {
  let needUseList = selectCheckList.value.filter(
    (item) => item["sourceType"] != "org"
  );
  let nodeList = selectOrgList.value;

  nodeList.forEach((item) => (item["sourceType"] = "org"));
  companiesList.value = nodeList;

  selectCheckList.value = [...needUseList, ...nodeList];
};
const clearWorkData = () => {
  let list = userStore.workerPositionList;
  list.forEach((item) => (item["isSelect"] = false));

  userStore.setWorkPosition(list);
};

const getIds = (data, status) => {
  let id = [];
  data.forEach((item, index) => {
    id.push(item.key);
    if (item.children) {
      getIds(item.children, status);
    }
  });

  orgChildIds.value.push(...id);
};
// 选中所有子级
const nodeSelectAll = (node, status) => {
  orgChildIds.value = [];
  let ids = orgIds.value;
  let arr = [...ids];
  let childrenIds = [];
  getIds(node.children, status);
  if (status) {
    // 选中
    arr.push(...orgChildIds.value);
  } else {
    // 取消
    if (node.children) {
      childrenIds = orgChildIds.value;
      ids = fiflterPackage(ids, childrenIds)
      arr = ids;
    }

  }
  arr = [...new Set(arr)];
  orgIds.value = arr;
  selectOrgList.value = []
  selectOrg(treeData.value, orgIds.value);
  checkChangeAllOrg();
};

// 选中当前
const nodeCurrentAll = (node, status) => {
  node.data.curSelect = status;
  let ids = orgIds.value;
  let arr = [...ids];
  let childIds = [];
  let curId = node.data.id;
  if (status) {
    // 选中
    if (node.children) {
      childIds = node.children.map((item) => item.key);
      arr.push(...childIds);
    } else {
      arr.push(curId);
    }
  } else {
    selectOrgList.value = unique(selectOrgList.value, 'id')
    // 取消
    if (node.children) {
      childIds = node.children.map((item) => item.key);
      ids = fiflterPackage(ids, childIds)
      arr = ids;
    } else {
      const findId = ids.findIndex((item) => item == curId);
      ids.splice(findId, 1);
      arr = ids;
    }

    node.data.allSelect = false;
  }

  orgIds.value = arr;
  selectOrgList.value = []
  selectOrg(treeData.value, orgIds.value);
  checkChangeAllOrg();
};

// 过滤
const fiflterPackage = (ids, list) => {
  ids = ids.filter((item) => {
    return list.every((itemB) => {
      return item !== itemB;
    });
  });
  return ids
}

const submit = () => {
  //  if (selectCheckList.value.length == 0) return ElMessage.error('请选择适用范围')

  let companies = [],
    positions = [],
    members = [],
    userList = [];
  let matchText = "";

  selectCheckList.value.forEach((item) => {
    if (item.isSelect || item["sourceType"] == "org") {
      item["sourceType"] == "work" &&
        positions.push({ code: item.code, name: item.name, curId: item.id });
      item["sourceType"] == "user" &&
        members.push({ email: item.email, name: item.label, curId: item.id });
      item["sourceType"] == "user" && userList.push(item);
      item["sourceType"] == "org" &&
        companies.push({ code: item.departmentId, name: item.label, curId: item.id });
      matchText += (item.name || item.label) + "、";
    }
  });
  let obj = {
    companies,
    positions,
    members,
    matchText,
    orgName: orgName.value,
    positionsIds: positionsIds.value,
    userList,
    membersIds: membersIds.value,
    companiesIds: companiesIds.value,
  };
  handleClose();
  clearWorkData();
  emit("on-update", [obj, matchText]);
};

// 岗位更新
const updateWork = (list) => {
  let newList = selectCheckList.value.filter(
    (item) => item["sourceType"] != "work"
  );
  selectCheckList.value = [...list, ...newList];
  console.log(list, "岗位数据");
  let ids = [];
  list.forEach((item) => {
    ids.push(item.id);
  });
  positionsIds.value = ids;
};

const getTagMainHeight = () => {
  let dom = document.getElementById("tagsMain");

  if (dom && dom.clientHeight) {
    if (dom.clientHeight > 39) {
      isShowBtn.value = true;
    } else {
      isShowBtn.value = false;
    }
  }
};
watch(
  () => selectCheckList.value,
  (newVal, oldVal) => {
    getTagMainHeight();
  },
  { immediate: true, deep: true }
);
defineExpose({
  submit
})
</script>
<style lang="scss" scoped>
.select-box {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.tags-box {
  overflow: hidden;
  flex: 1;
}

.tags-main {
  overflow: scroll;
}

.show-more {
  width: 50px;
  text-align: right;
  cursor: pointer;

  &:hover {
    color: var(--el-color-primary);
  }
}

.tree-box {
  display: flex;
  justify-content: space-between;
  width: 100%;
  align-items: center;

  p.btn-box {
    display: flex;
    align-items: center;
    margin: 0;

    span {
      font-size: 14px;

      &:nth-child(1) {
        margin-right: 20px;
      }
    }
  }
}

.search-input {
  padding: 10px 0;
}

.tabs,
.head {
  display: flex;
  height: 40px;
  align-items: center;
  border-bottom: 1px solid #dcdfe6;
  width: 100%;
  border-right: 1px solid #dcdfe6;

  p {
    margin: 0;
    font-size: 14px;
    margin: 0 14px;
    cursor: pointer;

    &.active {
      color: #0049ad;
      border-bottom: 1px solid #0049ad;
    }
  }
}

.head {
  border-right: 0;

  p {
    &:nth-child(1) {
      padding-left: 10px;
      flex: 1;
      color: #0049ad;
    }

    &:nth-child(2) {
      text-align: right;
    }
  }
}

.city-box {
  border-right: 1px solid #dcdfe6;
}

.filter-tree {
  height: 340px;
  overflow-y: auto;
  padding-bottom: 20px;
}

.selec-city {
  padding: 10px 0;
  height: 400px;
  overflow-y: auto;
  padding-bottom: 20px;
}

.subject-con {
  .subject-list {
    margin: 0;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #f5f5ff;
    padding: 0 10px;

    &:hover {
      background: #dcdfe6;
    }

    p {
      font-size: 14px;
      flex: 1;
      margin: 5px 0;
    }

    .check-box {
      img {
        width: 15px;
        height: 15px;
        margin-left: 15px;
        cursor: pointer;
      }
    }
  }
}

.tags {
  margin-right: 10px;
  margin-bottom: 10px;
}

.no-data {
  text-align: center;
  color: #666;
  font-size: 14px;
  margin-top: 40px;
}

.dialog-footer {
  text-align: right;
}

.search-list {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}
</style>
